package com.hmdp.utils;

import cn.hutool.core.lang.func.Func;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    private StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
//    存入缓存--解决序列化
    public  void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }
//    存入缓存--逻辑过期
    public  void setWithLogicexpire(String key, Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData=new RedisData();
        redisData.setObject(value);
        redisData.setExpire(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)) );
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透 通用代码
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallBack
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit unit) {
//       缓存中取数据
        String key=keyPrefix+id;
        String strjson = stringRedisTemplate.opsForValue().get(key);
//        取到了数据
        if(StrUtil.isNotBlank(strjson)) {
            return JSONUtil.toBean(strjson,type);
        }
        if(strjson !=null) {
            return  null;
        }
//        从数据库中查找数据
        R bean = dbFallBack.apply(id);
//        数据为空
        if(bean==null) {
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return  null;
        }
        this.set(key,bean,time,unit);
        return  bean;
    }

    /**
     * 逻辑过期
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallBack
     * @param time
     * @param timeUnit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R,ID> R queryWithLogicalEpriex(
            String keyPrefix, ID id, Class <R> type, Function<ID,R> dbFallBack,Long time, TimeUnit timeUnit)
    {
//        先从缓存中拿数据
        String key=keyPrefix+id;
        String strjson = stringRedisTemplate.opsForValue().get(key);
//        缓存中的数据为空
        if(StrUtil.isBlank(strjson)) {
            return  null;
        }
//        数据反序列化为Bean对象
        RedisData redisData = JSONUtil.toBean(strjson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getObject(), type);
        LocalDateTime expire = redisData.getExpire();
//        没有过期
        if(expire.isAfter(LocalDateTime.now())) {
            return r;
        }
//        过期了 先拿到锁
        boolean b = tryLock(RedisConstants.LOCK_SHOP_KEY+id);
//        获取成功
        if(b) {
//            开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
//                    重建缓存
                    R r1 = dbFallBack.apply(id);
                    this.setWithLogicexpire(key,r1,time,timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
//                    释放锁
                    unlock(RedisConstants.LOCK_SHOP_KEY + id);
                }
            });
        }
//        没拿到锁
        return r;


    }
    /**
     * 线程池
     */
    private  static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
//        setIfAbsent这个方法是key不存在才可以存储。key存在反而不能存储
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//        解决拆箱
        return BooleanUtil.isTrue(aBoolean);
    }

    /**
     * 释放锁
     * @param key
     */
    private  void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
